/*
* Copyright (c) 2012 Kyle Hayward
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

#include "Precompiled.h"
#include <ctime>

#include "Context.h"

#include "Variable.h"
#include "Program.h"
#include "Geometry.h"
#include "Buffer.h"

using namespace System;

namespace OptixDotNet 
{
	/// <summary>
	/// Provides types and methods for creating Optix ray-tracing programs
	/// </summary>
	private ref class NamespaceDoc
    {
    };

	Context::Context()
	{
		pin_ptr<RTcontext> ptr = &mContext;
		CheckError( rtContextCreate( ptr ) );

		StackSize = 1024; //set a default stack size

		mD3D9Device = IntPtr::Zero;
		mD3D10Device = IntPtr::Zero;
		mD3D11Device = IntPtr::Zero;
	}

	Context::~Context()
	{
		Destroy();
	}

	Context::!Context()
	{
		Destroy();
	}

	void Context::Compile()
	{
		Validate();
		CheckError( rtContextCompile( mContext ) );
	}

	void Context::SetRayGenerationProgram( int index, Program^ program )
	{
		CheckError( rtContextSetRayGenerationProgram( mContext, index, program->InternalPtr() ) );
	}

	void Context::SetRayMissProgram( int index, Program^ program )
	{
		CheckError( rtContextSetMissProgram( mContext, index, program->InternalPtr() ) );
	}

	void Context::SetExceptionProgram( int index, Program^ program )
	{
		CheckError( rtContextSetExceptionProgram( mContext, index, program->InternalPtr() ) );
	}

	generic< typename V >
	Geometry^ Context::CreateClusteredMesh(	unsigned int usePTX32InHost64, 
											unsigned int numTris,
											array<V>^ vertices,
											array<unsigned int>^ indices,
											array<unsigned int>^ materialIndices )
	{
		if( indices->Length != numTris * 3 )
			throw gcnew ArgumentOutOfRangeException( "indices", "indices.Length not equal to NumTris * 3" );

		if( indices->Length != materialIndices->Length )
			throw gcnew ArgumentOutOfRangeException( "indices/materialIndices", "indices.Length must equal materialIndices.Length" );

		pin_ptr<V> vPtr = &vertices[0];
		pin_ptr<unsigned int> iPtr = &indices[0];
		pin_ptr<unsigned int> mPtr = &materialIndices[0];

		RTgeometry geom;
		rtuCreateClusteredMesh( mContext, usePTX32InHost64, &geom, vertices->Length, (float*)vPtr, numTris, iPtr, mPtr );

		return gcnew Geometry( this, geom );
	}

	generic< typename V >
	Geometry^ Context::CreateClusteredMesh(	unsigned int usePTX32InHost64, 
											unsigned int numTris,
											array<V>^ vertices,
											Buffer^ normals,
											Buffer^ texcoords,
											array<unsigned int>^ indices,
											array<unsigned int>^ normalIndices,
											array<unsigned int>^ texcoordIndices,
											array<unsigned int>^ materialIndices )
	{
		if( indices->Length != numTris * 3 )
			throw gcnew ArgumentOutOfRangeException( "indices", "indices.Length not equal to NumTris * 3" );

		if( indices->Length != materialIndices->Length )
			throw gcnew ArgumentOutOfRangeException( "indices/materialIndices", "indices.Length must equal materialIndices.Length" );

		pin_ptr<V> vPtr = &vertices[0];
		pin_ptr<unsigned int> iPtr = &indices[0];
		pin_ptr<unsigned int> nPtr = &indices[0];
		pin_ptr<unsigned int> tcPtr = &indices[0];
		pin_ptr<unsigned int> mPtr = &materialIndices[0];

		RTgeometry geom;
		rtuCreateClusteredMeshExt(	mContext, usePTX32InHost64, &geom, vertices->Length, (float*)vPtr, numTris, iPtr, mPtr, 
									normals->InternalPtr(), nPtr, 
									texcoords->InternalPtr(), tcPtr );

		return gcnew Geometry( this, geom );
	}

	Variable^ Context::default::get( String^ s )
	{
		if( String::IsNullOrEmpty( s ) )
			throw gcnew Exception( "Context Error: Variable name is null or empty" );

		const char* str = (const char*)StrToAnsii( s );
		
		RTvariable rtVar;
		CheckError( rtContextQueryVariable( mContext, str, &rtVar ) );

		if( rtVar == 0 ) 
			CheckError( rtContextDeclareVariable( mContext, str, &rtVar ) );

		return gcnew Variable( this, rtVar );
	}

	void Context::default::set( String^ s, Variable^ var )
	{
		if( String::IsNullOrEmpty( s ) )
			throw gcnew Exception( "Context Error: Variable name is null or empty" );

		const char* str = (const char*)StrToAnsii( s );

		RTvariable rtVar;
		CheckError( rtContextQueryVariable( mContext, str, &rtVar ) );

		if( rtVar != 0 && var == nullptr )
		{
			if( var == nullptr )
			{
				CheckError( rtContextRemoveVariable( mContext, rtVar ) );
			}
		}
		else
		{
			throw gcnew Exception( "Context Error: Variable copying not yet implemented" );
		}
	}

	Variable^ Context::default::get( int index )
	{
		if( index < 0 || index >= VariableCount )
			throw gcnew ArgumentOutOfRangeException( "index" );
		
		RTvariable rtVar;
		CheckError( rtContextGetVariable( mContext, index, &rtVar ) );

		return gcnew Variable( this, rtVar );
	}

	void Context::default::set( int index, Variable^ var )
	{
		if( index < 0 || index >= VariableCount )
			throw gcnew ArgumentOutOfRangeException( "index" );

		RTvariable rtVar;
		CheckError( rtContextGetVariable( mContext, index, &rtVar ) );

		if( var == nullptr )
		{
			CheckError( rtContextRemoveVariable( mContext, rtVar ) );
		}
		else
		{
			throw gcnew Exception( "Context Error: Variable copying not yet implemented" );
		}
	}
}

